package cn.itcast.service.impl;

import cn.itcast.dao.UserDao;
import cn.itcast.entity.PageResult;
import cn.itcast.entity.QueryPageBean;
import cn.itcast.pojo.User;
import cn.itcast.service.UserService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service(version = "1.0.0")
public class UserServiceImpl implements UserService {


    @Autowired
    private UserDao userDao;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

            //设置分页参数
            PageHelper.startPage(currentPage,pageSize);
            //查询分页信息
            List<User> list = this.userDao.findPage(queryString);
            //封装分页信息
            PageInfo<User> pageInfo=new PageInfo<>(list);
            //给pageResult辅助
            PageResult pageResult=new PageResult((long)list.size(),pageInfo.getList());
            return pageResult;
    }

    @Override
    public User findById(Integer id) {
        return this.userDao.findById(id);
    }



    @Override
    public Integer deleteById(Integer id) {
        return this.userDao.deleteByUserId(id);
    }

    /**
     * 编辑用户
     * @param roleIds 角色id集合
     * @param user 用户信息
     * @return
     */
    @Override
    public Boolean handleEdit(int[] roleIds, User user) {
        //通过当前用户id， 删除t_user_role表中的数据
        int result = userDao.deleteById(user.getId());
        if (result > 0){
            //从新添加数据到t_user_role表中
            for (int i = 0; i < roleIds.length; i++) {
                //将用户对应的角色添加到t_user_role表中
                userDao.addToUserRole(user.getId(), roleIds[i]);
            }
        }
        //将用户信息跟新到数据库中
        int result1 = userDao.handleUpdate(user);

        return result1 > 0;
    }

    /**
     * 新建用户信息
     * @param user
     * @param roleIds
     * @return
     */
    @Override
    public Boolean handleAdd(User user, int[] roleIds) {

        //将用户信息跟新到数据库中
        int result = userDao.handleAdd(user);
        if (result == 1 && roleIds.length > 0){
            for (int i = 0; i < roleIds.length; i++) {
                //将用户对应的角色添加到t_user_role表中
                result = userDao.addToUserRole(user.getId(), roleIds[i]);
            }
        }
        return result > 0;

    }

}
